package com.yyge.controller.publicInterface;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.crypto.symmetric.AES;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yyge.controller.BaseController;
import com.yyge.controller.publicInterface.req.PublicInterfaceAddReq;
import com.yyge.controller.publicInterface.req.PublicInterfaceEditReq;
import com.yyge.controller.publicInterface.req.PublicInterfaceReq;
import com.yyge.controller.publicInterface.resp.PublicInterfaceResp;
import com.yyge.convertor.PublicInterfaceConvertor;
import com.yyge.dto.Query;
import com.yyge.dto.ResultCode;
import com.yyge.entity.PublicInterface;
import com.yyge.entity.User;
import com.yyge.service.PublicInterfaceService;
import com.yyge.dto.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yyge.service.UserService;
import com.yyge.util.StringUtil;
import com.yyge.vo.PageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.*;
import javax.crypto.spec.PSource;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;

@RestController
@RequestMapping("/publicinterface")
@Api(value = "通用存储相关接口",tags = "通用储存相关接口")
public class PublicInterfaceController extends BaseController<PublicInterface, PublicInterfaceResp, PublicInterfaceConvertor> {
    // 注入业务逻辑层
    private PublicInterfaceService service;

    @Autowired
    private UserService userService;


    @Autowired/*自动装配*/
    public void setService(PublicInterfaceService publicinterfaceService){
        this.service=publicinterfaceService;
    }

    @GetMapping/* GET(SELECT): 查询 */
    @ApiOperation(value = "通用储存分页查询",notes = "通用储存分页查询")
    public R<?> get(@Validated PublicInterfaceReq publicInterfaceReq, Query query) throws Exception  {
        User byId = userService.getById(publicInterfaceReq.getUserId());
        if(!byId.getStrKey().equals(publicInterfaceReq.getStrKey())){
            throw new RuntimeException("非法秘钥");
        }
        QueryWrapper<PublicInterface> wrapper = this.getWrapper(PublicInterfaceConvertor.MAPPER.ob2en(publicInterfaceReq));
        wrapper.eq("create_user",publicInterfaceReq.getUserId());
        Page<PublicInterface> page = this.query2Page(wrapper, query, (q, w) -> service.page(q, w));
        return R.ok( this.page2PageVo(page, PublicInterfaceConvertor.MAPPER::ob2respArr));
    }


    @PostMapping/* POST(CREATE): 新增&登陆 */
    @ApiOperation(value = "通用储存新增接口",notes = "通用储存新增接口")
    public R<?> post(@Validated @RequestBody PublicInterfaceAddReq addReq){
        PublicInterface entity = PublicInterfaceConvertor.MAPPER.ob2en(addReq);
        entity.setCreateUser(addReq.getUserId());
        entity.setUpdateUser(addReq.getUserId());
        User byId = userService.getById(addReq.getUserId());
        Optional.ofNullable(byId).orElseThrow(()->new RuntimeException("ID未授权"));
        if(!byId.getStrKey().equals(addReq.getStrKey())){
            throw new RuntimeException("非法秘钥");
        }
        PublicInterface queryEntity=new PublicInterface();
        queryEntity.setUserId(addReq.getUserId());
        List<PublicInterface> list = service.list(new QueryWrapper<>(queryEntity));
        if(list.size()>2){
             throw new RuntimeException("用户最多只支持上传两个表单");
        }

        boolean i=service.save(entity);
        return i?R.ok("新增成功！"):R.error(ResultCode.SYSTEM_SERVICE_ADD_ERROR);
    }

    @GetMapping("/detail")
    @ApiOperation(value ="通用储存详情",notes = "通用储存详情")
    public R<?> detail(String UserId,String id){
        User byId = userService.getById(UserId);
        Optional.ofNullable(byId).orElseThrow(()->new RuntimeException("ID未授权"));
        PublicInterface one = service.getById(id);
        Optional.ofNullable(one).orElseThrow(()->new RuntimeException("您暂时没有创建通用存储表单"));
        return R.ok(one);
    }


    @PutMapping/* POST(CREATE): 更新 */
    @ApiOperation(value = "通用存储修改",notes = "通用存储修改")
    public R<?> edit(@Validated @RequestBody PublicInterfaceEditReq editReq){
        User byId = userService.getById(editReq.getUserId());
        if(byId.getStrKey().equals(editReq.getStrKey())){
            throw new RuntimeException("非法秘钥");
        }
        PublicInterface publicInterface = PublicInterfaceConvertor.MAPPER.ob2en(editReq);
        boolean i=service.updateById(publicInterface);
        return i?R.ok("修改成功！"):R.error(ResultCode.SYSTEM_SERVICE_MODIFY_ERROR);
    }

    @PatchMapping/* PUT(UPDATE): 部分更新 */
    public R patch(@RequestBody PublicInterface publicinterface){
        return null;
    }

    @DeleteMapping("/{id}")/* DELETE(DELETE): 删除 && 批量删除 */
    public R delete(@PathVariable("id") Long[] list){
        boolean i = service.removeByIds(Arrays.asList(list));
        return i?R.ok("修改成功！"):R.error(ResultCode.SYSTEM_SERVICE_DELETE_ERROR);
    }
}


